/**
 * @author 
 * @time 2022-04-19 19PM
 * @description 项目配置文件目录
 */
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

/** 引入store实例 */
import store from '../store'

/** 解决push的错误方法，需要重写push方法 */
const pushPlugin = Router.prototype.push
Router.prototype.push = function(_params) {
    // console.log('----------------- push方法');
    pushPlugin.call(this, _params).catch(e => {
        console.log('------------------------ 重写push')
            // console.log(e)
    })
}

/** 动态路由注册 */
const Login = () =>
    import ('../pages/login/index.vue')
const Register = () =>
    import ('../pages/login/register.vue')
const Home = () =>
    import ('../pages/home/container.vue')
const Cart = () =>
    import ('../pages/cart')
const HarAddress = () =>
    import ('../pages/addressset/harvestAddress.vue')
const AddSite = () =>
    import ('../pages/addressset/addSite.vue')
const Install = () =>
    import ('../pages/addressset/install.vue')
const List = () =>
    import ('../pages/list')
const Details = () =>
    import ('../pages/details')



const menuList = [
    { name: '首页', path: '/index/home' },
    { name: '分类', path: '/index/type' },
    { name: '视频', path: '/index/videos' },
    { name: '购物车', path: '/index/cart' },
    { name: '我的', path: '/index/me' },
]

let indexRoutes = []
menuList.forEach(it => {
    let _path = it.path.replace('/index/', '')
    indexRoutes.push({
        path: _path,
        component: () =>
            import (`../pages/${_path}`)
    })
})


/** 实例化路由 */
const router = new Router({
    // mode: history,
    routes: [
        { path: '/', redirect: '/login' },
        { path: '/login', component: Login, meta: { needLogin: false } },
        { path: '/register', component: Register, meta: { needLogin: false } },
        { path: '/cart', component: Cart, meta: { needLogin: false } },

        { path: '/harvestAddress', component: HarAddress },
        //收货地址
        { path: '/addSite', component: AddSite },
        // 设置
        { path: '/install', component: Install },

        { path: '/list', component: List },
        { path: '/details', component: Details },

        //协议路由
        { path: '/suggest', component: () => import ('../pages/login/suggest.vue'),meta: { needLogin: false } },
        //搜索路由
        {path:'/search',component: () => import ('../pages/search')},
        
        {
            path: '/home',
            component: Home,

            children: [
                { path: '', redirect: 'home' },
                ...indexRoutes
            ]
        },

    ]
})

/** 全局拦截路由配置 */

router.beforeEach((to, from, next) => {
    //判断是否需要登录拦截
    let needLogin = to.meta.needLogin
    if (needLogin === false) {
        next()
        return
    }

    /** 从vuex中取数据，根据token判断是否存在 */
    let flag = store.getters['common/token']
    if (!!flag) {
        console.log(flag);
        next()
        return
    }

    //重定向到login页面
    next('/login')
})
export default router